package com.divemotor.ventarepuestosinternet.util.converter;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.ConverterException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.divemotor.ventarepuestosinternet.model.TipoVehiculo;
import com.divemotor.ventarepuestosinternet.service.TipoVehiculoService;
import com.divemotor.ventarepuestosinternet.util.Constantes;

@Component("tipoVehiculoConverter")
public class TipoVehiculoConverter implements Converter {
	
	@Autowired
	TipoVehiculoService tipoVehiculoService;
	

	@Override
	public Object getAsObject(FacesContext context, UIComponent component,String value) {
		if (value.trim().equals("")) {
			return null;
		}else{
			try {
				if(value.equals(Constantes.NO_SELECCIONADO.toString())){
					return new TipoVehiculo(Constantes.NO_SELECCIONADO.toString(), Constantes.NO_SELECCIONADO_ETIQUETA);
				}else{
					TipoVehiculo tipoVehiculo = tipoVehiculoService.obtenerPorCodigo(new TipoVehiculo(value, ""));
					return tipoVehiculo;
				}
			} catch (Exception e) {
				throw new ConverterException(new FacesMessage(FacesMessage.SEVERITY_ERROR, "Conversion Error", "No es un tipo de Vehiculo valido"));
			}
		}	
	}

	@Override
	public String getAsString(FacesContext context, UIComponent component,Object value) {
		if (value == null) {
			return null;
		}else{
			TipoVehiculo tipo = (TipoVehiculo) value;
        	String submittedValue = tipo.getCodigoTipoVehiculo();
            return submittedValue;
		}
	}

}
